package hyl.xsdk.flutter.plugin.xsdk_flutter_plugin.second_screen;


import android.app.Presentation;
import android.content.Context;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Display;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.NonNull;
import java.util.Map;

import hyl.xsdk.flutter.plugin.xsdk_flutter_plugin.base.XBeanPluginMethod;
import hyl.xsdk.sdk.api.android.Android_API;
import hyl.xsdk.sdk.api.android.other_api.eventbus.XEventBusUtils;
import hyl.xsdk.sdk.api.android.other_api.eventbus.XEvent_EventBus;
import hyl.xsdk.sdk.api.android.utils.L;
import hyl.xsdk.sdk.api.android.utils.json.XJsonUtils;
import hyl.xsdk.sdk.api.android.webview.XJSInterfaseObjectDialog;
import hyl.xsdk.sdk.framework.controller.base.XIRelease;
import hyl.xsdk.sdk.framework.controller.support.XWeakHandler;
import hyl.xsdk.sdk.framework.view.subview.XWebView_onScrollChangedCallback;
import io.flutter.plugin.common.MethodChannel;

/*
第二屏幕,分屏,实际是将dialog显示到分屏上
睿本flutter收银端使用,
注意:
1.分屏使用android原生,js交互同原生android一样
2.在分屏中不能使用主屏的MethodChannel通知原生,会报错提示不是主屏,改为使用
 */
public class XSecondScreen_flutter_webview_reabam extends Presentation implements XIRelease {

    public Android_API api;
    public String webURL;

    XWebView_onScrollChangedCallback webView;



    public XSecondScreen_flutter_webview_reabam(
            Context outerContext,
            Display display, //第二屏幕: XDialogSecondScreenUtils.getPresentationDisplay();
            String webURL
    ) {
        super(outerContext, display);
        this.webURL=webURL;
    }

    public String javascriptInterfaceName="JSInterfaceObj";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        try{
            L.sdk("-------------- "+this.getClass().getName()+" onCreate() --------------");
            api = Android_API.getInstance(getContext());
            //初始化一个HandlerThread
            initHandlerThread();

            webView =new XWebView_onScrollChangedCallback(getContext());
            setContentView(webView);

            api.initWebView(webView,webViewClient,webChromeClient,xjsInterfaseObject,javascriptInterfaceName,webURL);


        }catch (Exception e){
            L.sdk(e);
        }
    }


    //原生发送通知flutter
    private void sendMessageByEvenBus(String tag, Object arguments){
        XEvent_EventBus event=new XEvent_EventBus();
        event.tag=tag;
        event.obj=arguments;
        XEventBusUtils.postEvent(event);
    }

    public XJSInterfaseObjectDialog xjsInterfaseObject=new XJSInterfaseObjectDialog(){
        @JavascriptInterface
        public void getH5SaveValue(final String key) {
            //h5本地通用保存
            xWorkHandler.post(new Runnable() {
                @Override
                public void run() {
                    //通知flutter
                    XBeanPluginMethod data=new XBeanPluginMethod();
                    data.type="getH5SaveValue";
                    data.data=key;
                    sendMessageByEvenBus("XSecondScreen", data);
                }
            });

        }

        //是否快速收银////////////////////////////////////////////////////
        @JavascriptInterface
        public boolean getIsQuickCash() {
            //是否快速收银(h5本地保存使用)
            L.sdk("---分屏h5,getIsQuickCash");
            return true;
        }

        @JavascriptInterface
        public void getOfflineShopCart(){
            //获得离线数据:购物车
            L.sdk("---分屏h5,getOfflineShopCart");
            XBeanPluginMethod data=new XBeanPluginMethod();
            data.type="getOfflineShopCart";
            sendMessageByEvenBus("XSecondScreen",data);
        }

    };


    //调用h5方法通知刷新h5界面
    public void refreshH5WebView(){
        xWorkHandler.post(new Runnable() {
            @Override
            public void run() {
                L.sdk("---分屏通知h5,javascript:cacheGet()");
                webView.loadUrl("javascript:cacheGet()");
            }
        });
    }

    //调用h5方法通知刷新h5界面
    public void h5GetShoppingCart(String json){
        xWorkHandler.post(new Runnable() {
            @Override
            public void run() {
                L.sdk("---第二屏获得第一屏购物车json="+json);
                webView.loadUrl("javascript:getOfflineDataCallback('offlineShopcart','"+json+"')");
            }
        });
    }
    public void h5GetSaveValue(String key, String value){
        xWorkHandler.post(new Runnable() {
            @Override
            public void run() {
                L.sdk("---第二屏获得第一屏h5savevalue,key="+key+",value="+value);
                webView.loadUrl("javascript:getAppValue('"+key+"','"+value+"')");
            }
        });
    }



    @Override
    protected void onStart() {
        super.onStart();
    }


    @Override
    protected void onStop() {
        super.onStop();
        L.sdk("---------------"+getClass().getSimpleName()+" onStop----------------");
        xReleaseReference();
    }


    //显示到分屏上
    @Override
    public void show() {
        super.show();
    }

    //关闭
    @Override
    public void dismiss() {
        super.dismiss();
    }

    //释放资源
    @Override
    public void xReleaseReference() {
        try{
            if (xWorkHandler!=null){
                xWorkHandler.removeCallbacksAndMessages(null);
            }
        }catch (Exception e){
            L.sdk(e);
        }


    }

    /////////////////////////////////////


    public XWeakHandler xWorkHandler;//HandlerThread子线程里的Handler
    //默认初始化一个HandlerThread,workHandler默认可使用
    private void initHandlerThread(){

        if(xWorkHandler==null){
            xWorkHandler=new XWeakHandler(new Handler.Callback() {
                @Override
                public boolean handleMessage(@NonNull Message msg) {
                    return false;
                }
            });
        }

    }



    public WebViewClient webViewClient=new WebViewClient(){

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            L.sdk("webView shouldOverrideUrlLoading...");
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            L.sdk("webView onPageFinished...");
//            hideLoad();
//            srfl.setRefreshing(false);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            //注意在android 6.0以下不回调
            L.sdk(".....webView onReceivedError...");
            super.onReceivedError(view, request, error);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            L.sdk(".....webView onReceivedError2,errorCode="+errorCode+",description="+description+",failingUrl="+failingUrl);
            //注意在android 6.0以下不回调
            super.onReceivedError(view, errorCode, description, failingUrl);

            //这里页面重置空白,注意: 后面刷新时不能直接view.reload();因为以重置url为空白页, 要使用view.loadUrl(failingUrl或指定url);
            view.loadUrl("about:blank");

            //通知webview加载出错,弹占位图覆盖,点击重新加载失败的failingUrl:  view.loadUrl(failingUrl或指定url);
            //notifyWebViewLoadUrlError(errorCode,description,failingUrl);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            L.sdk(".....webView onReceivedSslError...");
            //注意在android 6.0以下不回调
            //super.onReceivedSslError(view, handler, error);//默认webView变成空白
            handler.proceed();//接受正式

        }

        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            //注意在android 6.0以下不回调
            L.sdk("webView onReceivedHttpError...");
            super.onReceivedHttpError(view, request, errorResponse);
        }

    };

    WebChromeClient webChromeClient =new WebChromeClient(){
        @Override
        public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
            L.sdk("webView onCreateWindow...");
            return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg);
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            L.sdk("webView onJsAlert...");
            return super.onJsAlert(view, url, message, result);
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
            L.sdk("webView onJsConfirm...");
            return super.onJsConfirm(view, url, message, result);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            //android 6.0以下通过这个方法判断铺货404等错误
			/*
			if(!TextUtils.isEmpty(title)&&title.toLowerCase().contains("error")){
              loadError = true;
          }
			 */
            L.sdk("webView onReceivedTitle...title="+title);
            super.onReceivedTitle(view, title);
        }

    };



}
